// webSocketService.ts
import { ElMessage } from "element-plus";
import { userStore } from "../store/userStore";
import { chatStore } from "../store/chatStore";
import { handleMessage } from "./websocketMessage/handleReceiveMessage";



export const connectWebSocket = () => {
    const token = encodeURIComponent(userStore().userInfo.token);
    const websocket = new WebSocket(`ws://localhost:8080/websocket?token=${token}`);

    websocket.binaryType = 'arraybuffer';       // 显示设置为ayyayBuffer数据类型

    websocket.onopen = () => {
        // console.log("WebSocket 连接成功");
    };

    websocket.onmessage = (event) => {
        if (typeof event.data === 'string') {
            try {
                const data = JSON.parse(event.data);
                let chatType = data.type;
                handleMessage(chatType, data);
            } catch (error) {
                console.error(error)
            }
        } else if (event.data instanceof Blob) {
            console.log("是blob数据")
        } else if (event.data instanceof ArrayBuffer) {
            const arrayBuffer = event.data;
            const headerSize = 256; // 消息头大小
            const header = new Uint8Array(arrayBuffer.slice(0, headerSize));
            const fileContent = new Uint8Array(arrayBuffer.slice(headerSize));

            // 解析消息头中的文件名、文件大小等信息
            const senderId = new TextDecoder('utf-8').decode(header.slice(0, 15)).trim();
            const rawFileName = new TextDecoder('utf-8').decode(header.slice(15, 65)).trim(); // 文件名从第15字节开始，长度为50字节
            const fileName = rawFileName.replace(/\*/g, '').trim();     // 去除所有星号
            // 从 DataView 中读取64位文件大小
            const fileSizeBuffer = header.slice(65, 73); // 文件大小从第65字节开始，长度为8字节
            const fileSizeView = new DataView(fileSizeBuffer.buffer);
            const fileSize = fileSizeView.getBigUint64(0);

            // 解析单位字段（最多4字节，去掉尾部的空格）
            const unitBytes = header.slice(73, 77); // 单位从第73字节开始，长度为4字节
            const unit = new TextDecoder('utf-8').decode(unitBytes).trim().replace(/\s+$/, '');
            // 解析fileKey（固定长度为20字节）
            const fileKeyBytes = header.slice(77, 97);   // filekey在二进制数据中的第77个字节开始，固定长度20
            const fileKey = new TextDecoder('utf-8').decode(fileKeyBytes);
            // 处理文件
            disposeFile(fileName, fileContent, senderId, fileKey);
        } else {
            ElMessage.warning("未知的数据类型");
        }
    };

    websocket.onerror = (error) => {
        console.error("WebSocket 连接错误：", error);
    };

    websocket.onclose = () => {
        console.log("WebSocket 连接关闭");
    };


    return websocket;
};




// 处理照片文件的函数
function disposeFile(fileName: string, fileContent: Uint8Array, senderId: string, fileKey: string) {
    if (fileName.toLowerCase().endsWith(('.jpg')) || fileName.endsWith('png') || fileName.endsWith('.jpeg') ||
        fileName.endsWith('gif') || fileName.endsWith('txt') || fileName.endsWith('pdf')) {
        // 处理照片文件的后缀       如果文件名不存在'.'时会返回undefined，所以这里需要一个默认值unknown
        const fileExtension = fileName.split(".").pop()?.toLowerCase() || "unknown";
        // 根据文件后缀设置blob的MIME类型
        let mimeType;
        switch (fileExtension) {
            case 'jpg':
            case 'jpeg':
                mimeType = 'image/jpeg';
                break;
            case 'png':
                mimeType = 'image/png';
                break;
            case 'gif':
                mimeType = 'image/gif'
                break;
            case 'txt':
                mimeType = 'text/plain';
                break;
            case 'pdf':
                mimeType = 'application/pdf';
                break;
            default:
                mimeType = 'application/octet-binary';      // 默认类型
                break;
        }
        // 将文件内容转换为blob对象
        const blob = new Blob([fileContent], { type: mimeType });// 根据文件类型设置 MIME 类型

        // 生成文件链接
        const fileUrl = URL.createObjectURL(blob);

        // 构建文件信息对象
        const fileInfo = {
            senderId: senderId,
            fileName: fileName,
            fileUrl: fileUrl,
            receivedId: userStore().userInfo.uu_id,
            fileExtension: fileExtension,
            mimeType: mimeType,
            fileKey: fileKey,
            timeStamp: new Date().toISOString()
        }
        chatStore().setFileInfo(fileInfo);
    }
}


